package cn.javaex.hgo.config.shiro;

import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.springframework.beans.factory.annotation.Autowired;

import cn.javaex.hgo.action.system.dao.hgo_menu_info.IHgoMenuInfoDAO;
import cn.javaex.hgo.action.system.view.HgoUserInfo;
import cn.javaex.hgo.util.HgoStringUtils;

/**
 * 权限拦截器
 * 此处用于拦截用户访问具有权限的菜单
 * 
 * @author 陈霓清
 */
public class AccessFilter extends AdviceFilter {
	
	@Autowired
	private IHgoMenuInfoDAO iHgoMenuInfoDAO;
	
	public boolean preHandle(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		
		// 1.0 获取当前应用项目名
		String domain = request.getSession().getServletContext().getContextPath();
		
		// 2.0 取出用户信息
		Subject subject = SecurityUtils.getSubject();
		if (!subject.isAuthenticated()) {
			// 登录状态已失效，重定向到登录页
			response.sendRedirect(domain+"/login.action");
			return false;
		}
		HgoUserInfo userInfo = (HgoUserInfo)subject.getPrincipal();
		
		// 3.0 路径处理
		// 3.1 获取当前访问路径
		String url = request.getRequestURI();
		// 3.2 对路径进行处理
		// 3.2.1 去除路径中的项目名
		url = url.replaceFirst(domain, "");
		// 3.2.2 格式化url
		url = HgoStringUtils.formatUrl(url);
		// 如果不是页面跳转链接，则直接放过
		if (url.indexOf(".action")==-1) {
			return true;
		}
		// 如果是首页，也放过
		if ("index.action".equals(url)) {
			return true;
		}
		
		// 4.0 查询所有菜单路径
		Set<String> allMenuUrlSet = iHgoMenuInfoDAO.listMenuUrl();
		// 4.1 判断当前访问路径是否是菜单链接
		if (allMenuUrlSet.contains(url)) {
			// 权限验证
			// 4.2 获取用户拥有的菜单路径
			Set<String> userMenuUrlSet = userInfo.getMenuUrlSet();
			if (userMenuUrlSet!=null && userMenuUrlSet.isEmpty()==false && userMenuUrlSet.contains(url)) {
				return true;
			} else {
				// 跳转到没有权限页面
				request.getRequestDispatcher("/WEB-INF/page/error/unauthorize.jsp").forward(request, response);
				return false;
			}
		}
		
		return true;
	}
	
}
